package org.springframework.session;

import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;

public class PrincipalNameIndexResolver<S extends Session> extends SingleIndexResolver<S> {

	private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";

	private static final Expression expression = new SpelExpressionParser().parseExpression("authentication?.name");

	public PrincipalNameIndexResolver() {
		super(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
	}

	public String resolveIndexValueFor(S session) {
		String principalName = session.getAttribute(getIndexName());
		if (principalName != null) {
			return principalName;
		}
		Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT);
		if (authentication != null) {
			return expression.getValue(authentication, String.class);
		}
		return null;
	}
}
